"""
DatabaseServer 适配器
为 ExecutionEngine 提供标准化的数据库服务接口
"""

from typing import List, Dict, Any, Iterator, Optional
import sys
import os

# 添加当前目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.insert(0, current_dir)

try:
    from database_server import DatabaseServer, DatabaseConfig
    from table_schema import Column, ColumnType
    from storage_engine import CachePolicy
    from statistics import Logger
except ImportError as e:
    print(f"Import error in database_server_adapter: {e}")
    raise


class DatabaseServerAdapter:
    """
    DatabaseServer 适配器
    
    为 ExecutionEngine 提供统一的数据库服务接口，
    内部调用 DatabaseServer 的多数据库架构
    """
    
    def __init__(self, data_root: str = "./data", 
                 cache_size: int = 100,
                 cache_policy: CachePolicy = CachePolicy.LRU,
                 enable_locking: bool = True,
                 max_query_workers: int = 4,
                 max_io_workers: int = 2,
                 connection_timeout: int = 30):
        """
        初始化数据库服务器适配器
        
        Args:
            data_root: 数据根目录
            cache_size: 缓存大小
            cache_policy: 缓存策略
            enable_locking: 是否启用锁机制
            max_query_workers: 最大查询工作线程数
            max_io_workers: 最大IO工作线程数
            connection_timeout: 连接超时时间
        """
        self.logger = Logger()
        
        # 创建数据库服务器配置
        config = DatabaseConfig(
            db_path=data_root,
            cache_size=cache_size,
            cache_policy=cache_policy,
            enable_locking=enable_locking,
            max_query_workers=max_query_workers,
            max_io_workers=max_io_workers,
            connection_timeout=connection_timeout
        )
        
        # 创建数据库服务器
        self.database_server = DatabaseServer(config)
        
        # 启动数据库服务器
        self.database_server.start()
        
        # 会话管理
        self.session_id = None
        self.current_database = None
        
        # 认证管理
        self.is_authenticated = False
        self.current_username = None
        self.current_user_host = None
        
        self.logger.info("ADAPTER", 0, f"DatabaseServerAdapter initialized with data root: {data_root}")
    
    def connect(self, database_name: str = None) -> str:
        """
        建立连接并可选择指定数据库（向后兼容，不推荐使用）
        
        Args:
            database_name: 要连接的数据库名称（可选）
            
        Returns:
            str: 会话ID
        """
        self.logger.warn("ADAPTER", 0, "connect() is deprecated, use login() for authenticated connections")
        
        if self.session_id:
            self.logger.warn("ADAPTER", 0, "Already connected, closing existing session")
            self.disconnect()
        
        # 创建新会话
        self.session_id = self.database_server.create_session()
        self.logger.info("ADAPTER", 0, f"Created session: {self.session_id}")
        
        # 如果指定了数据库，自动切换
        if database_name:
            self.use_database(database_name)
        
        return self.session_id
    
    def login(self, username: str, password: str, client_host: str = None, 
              database_name: str = None) -> bool:
        """
        用户登录认证
        
        Args:
            username: 用户名
            password: 密码
            client_host: 客户端主机
            database_name: 要连接的数据库名称（可选）
            
        Returns:
            bool: 认证是否成功
        """
        try:
            if self.session_id:
                self.logger.warn("ADAPTER", 0, "Already connected, closing existing session")
                self.disconnect()
            
            # 进行用户认证并创建会话
            self.session_id = self.database_server.authenticate_and_create_session(
                username, password, client_host
            )
            
            if self.session_id:
                self.is_authenticated = True
                self.current_username = username
                self.current_user_host = client_host or '%'
                
                self.logger.info("ADAPTER", 0, f"User {username} authenticated successfully, session: {self.session_id}")
                
                # 如果指定了数据库，自动切换
                if database_name:
                    success = self.use_database(database_name)
                    if not success:
                        self.logger.warn("ADAPTER", 0, f"Failed to switch to database {database_name} after login")
                
                return True
            else:
                self.logger.warn("ADAPTER", 0, f"Authentication failed for user {username}")
                return False
                
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Login error: {e}")
            return False
    
    def logout(self):
        """用户注销"""
        try:
            if self.session_id:
                self.database_server.close_session(self.session_id)
                self.logger.info("ADAPTER", 0, f"User {self.current_username} logged out")
            
            self._reset_state()
            
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Logout error: {e}")
            self._reset_state()
    
    def _reset_state(self):
        """重置适配器状态"""
        self.session_id = None
        self.current_database = None
        self.is_authenticated = False
        self.current_username = None
        self.current_user_host = None
    
    def disconnect(self):
        """断开连接"""
        if self.session_id:
            self.database_server.close_session(self.session_id)
            self.logger.info("ADAPTER", 0, f"Closed session: {self.session_id}")
        
        self._reset_state()
    
    def create_database(self, database_name: str, charset: str = "utf8") -> bool:
        """
        创建数据库
        
        Args:
            database_name: 数据库名称
            charset: 字符集
            
        Returns:
            bool: 创建是否成功
        """
        if not self.session_id:
            raise RuntimeError("Not connected, call connect() first")
        
        success = self.database_server.create_database(self.session_id, database_name, charset)
        if success:
            self.logger.info("ADAPTER", 0, f"Created database: {database_name}")
        return success
    
    def drop_database(self, database_name: str, force: bool = False) -> bool:
        """
        删除数据库
        
        Args:
            database_name: 数据库名称
            force: 是否强制删除
            
        Returns:
            bool: 删除是否成功
        """
        if not self.session_id:
            raise RuntimeError("Not connected, call connect() first")
        
        success = self.database_server.drop_database(self.session_id, database_name, force)
        if success:
            self.logger.info("ADAPTER", 0, f"Dropped database: {database_name}")
            # 如果删除的是当前数据库，清除上下文
            if self.current_database == database_name:
                self.current_database = None
        return success
    
    def use_database(self, database_name: str) -> bool:
        """
        切换当前数据库
        
        Args:
            database_name: 数据库名称
            
        Returns:
            bool: 切换是否成功
        """
        if not self.session_id:
            raise RuntimeError("Not connected, call connect() first")
        
        success = self.database_server.use_database(self.session_id, database_name)
        if success:
            self.current_database = database_name
            self.logger.info("ADAPTER", 0, f"Switched to database: {database_name}")
        return success
    
    def list_databases(self) -> List[str]:
        """获取数据库列表"""
        if not self.session_id:
            raise RuntimeError("Not connected, call connect() first")
        
        return self.database_server.list_databases(self.session_id)
    
    def get_current_database(self) -> Optional[str]:
        """获取当前数据库名称"""
        return self.current_database
    
    # ==================== 表操作接口 ====================
    
    def create_table(self, table_name: str, columns) -> bool:
        """
        创建表
        
        Args:
            table_name: 表名
            columns: 列定义（支持多种格式）
            
        Returns:
            bool: 创建是否成功
        """
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database, call connect() and use_database() first")
        
        # 转换列定义格式
        os_columns = self._convert_columns(columns)
        
        try:
            success = self.database_server.execute_database_operation(
                self.session_id, "create_table", 
                table_name=table_name, 
                columns=os_columns
            )
            if success:
                self.logger.info("ADAPTER", 0, f"Created table: {table_name}")
            return success
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to create table {table_name}: {e}")
            return False
    
    def drop_table(self, table_name: str) -> bool:
        """删除表"""
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database")
        
        try:
            success = self.database_server.execute_database_operation(
                self.session_id, "drop_table", 
                table_name=table_name
            )
            if success:
                self.logger.info("ADAPTER", 0, f"Dropped table: {table_name}")
            return success
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to drop table {table_name}: {e}")
            return False
    
    def select_records(self, table_name: str, condition: Dict = None) -> List[Dict[str, Any]]:
        """
        查询记录
        
        Args:
            table_name: 表名
            condition: 查询条件
            
        Returns:
            List[Dict]: 查询结果列表
        """
        if not self.session_id:
            raise RuntimeError("Not connected to database server")
        
        if not self.current_database:
            raise RuntimeError("No database selected")
        
        try:
            result = self.database_server.execute_database_operation(
                self.session_id,
                "select_records",
                table_name=table_name,
                condition=condition
            )
            
            return result if result is not None else []
            
        except Exception as e:
            self.logger.error("SELECT", 0, f"Select records failed: {e}")
            return []
    
    def insert_record(self, table_name: str, record: Dict[str, Any]) -> bool:
        """插入记录"""
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database")
        
        try:
            success = self.database_server.execute_database_operation(
                self.session_id, "insert_record", 
                table_name=table_name, 
                record_data=record
            )
            if success:
                self.logger.info("ADAPTER", 0, f"Inserted record into table: {table_name}")
            return success
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to insert record into {table_name}: {e}")
            return False
    
    def scan_table(self, table_name: str, 
                   columns: Optional[List[str]] = None,
                   condition: Optional[Dict] = None) -> Iterator[Dict[str, Any]]:
        """
        扫描表数据
        
        Args:
            table_name: 表名
            columns: 投影列（None表示所有列）
            condition: 过滤条件
            
        Yields:
            Dict[str, Any]: 记录
        """
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database")
        
        try:
            records = self.database_server.execute_database_operation(
                self.session_id, "select_records", 
                table_name=table_name, 
                condition=condition
            )
            
            if records:
                for record in records:
                    # 应用列过滤
                    if columns and '*' not in columns:
                        filtered_record = {col: record.get(col) for col in columns if col in record}
                        yield filtered_record
                    else:
                        yield record
            
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to scan table {table_name}: {e}")
            return iter([])
    
    def update_records(self, table_name: str, condition: Dict, updates: Dict) -> int:
        """更新记录"""
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database")
        
        try:
            updated_count = self.database_server.execute_database_operation(
                self.session_id, "update_records", 
                table_name=table_name, 
                condition=condition, 
                updates=updates
            )
            self.logger.info("ADAPTER", 0, f"Updated {updated_count} records in table: {table_name}")
            return updated_count or 0
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to update records in {table_name}: {e}")
            return 0
    
    def delete_records(self, table_name: str, condition: Dict) -> int:
        """删除记录"""
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database")
        
        try:
            deleted_count = self.database_server.execute_database_operation(
                self.session_id, "delete_records", 
                table_name=table_name, 
                condition=condition
            )
            self.logger.info("ADAPTER", 0, f"Deleted {deleted_count} records from table: {table_name}")
            return deleted_count or 0
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to delete records from {table_name}: {e}")
            return 0
    
    def list_tables(self) -> List[str]:
        """获取表列表"""
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database")
        
        try:
            return self.database_server.execute_database_operation(
                self.session_id, "list_tables"
            ) or []
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to list tables: {e}")
            return []
    
    def get_table_info(self, table_name: str) -> Optional[Dict]:
        """获取表信息"""
        if not self.session_id or not self.current_database:
            raise RuntimeError("Not connected to database")
        
        try:
            return self.database_server.execute_database_operation(
                self.session_id, "get_table_schema", 
                table_name=table_name
            )
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to get table info for {table_name}: {e}")
            return None
    
    # ==================== 事务接口 ====================
    
    def begin_transaction(self) -> str:
        """开始事务"""
        if not self.session_id:
            raise RuntimeError("Not connected")
        
        return self.database_server.begin_transaction(self.session_id)
    
    def commit_transaction(self):
        """提交事务"""
        if not self.session_id:
            raise RuntimeError("Not connected")
        
        self.database_server.commit_transaction(self.session_id)
    
    def rollback_transaction(self):
        """回滚事务"""
        if not self.session_id:
            raise RuntimeError("Not connected")
        
        self.database_server.rollback_transaction(self.session_id)
    
    # ==================== 统计和监控 ====================
    
    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        return self.database_server.get_server_stats()
    
    def _convert_columns(self, columns) -> List[Column]:
        """
        转换列定义为内部格式
        
        Args:
            columns: 列定义（支持多种格式）
            
        Returns:
            List[Column]: 转换后的列定义
        """
        os_columns = []
        
        for col in columns:
            if isinstance(col, Column):
                # 已经是 Column 对象
                os_columns.append(col)
            elif isinstance(col, dict):
                # 从字典格式转换
                col_name = col.get('name')
                col_type = col.get('type', 'VARCHAR').upper()
                col_length = col.get('length')
                col_nullable = col.get('nullable', True)
                col_primary_key = col.get('primary_key', False)
                
                # 转换类型
                if col_type in ['INT', 'INTEGER']:
                    os_col_type = ColumnType.INT
                    os_column = Column(col_name, os_col_type, nullable=col_nullable, primary_key=col_primary_key)
                elif col_type in ['VARCHAR', 'STRING', 'TEXT']:
                    os_col_type = ColumnType.VARCHAR
                    # VARCHAR类型需要长度，默认设置为255
                    length = col_length if col_length else 255
                    os_column = Column(col_name, os_col_type, length=length, nullable=col_nullable, primary_key=col_primary_key)
                elif col_type in ['FLOAT', 'DOUBLE']:
                    os_col_type = ColumnType.FLOAT
                    os_column = Column(col_name, os_col_type, nullable=col_nullable, primary_key=col_primary_key)
                elif col_type in ['BOOLEAN', 'BOOL']:
                    os_col_type = ColumnType.BOOLEAN
                    os_column = Column(col_name, os_col_type, nullable=col_nullable, primary_key=col_primary_key)
                elif col_type in ['DATE', 'DATETIME']:
                    os_col_type = ColumnType.DATE
                    os_column = Column(col_name, os_col_type, nullable=col_nullable, primary_key=col_primary_key)
                else:
                    # 默认VARCHAR类型，长度255
                    os_col_type = ColumnType.VARCHAR
                    os_column = Column(col_name, os_col_type, length=255, nullable=col_nullable, primary_key=col_primary_key)
                
                os_columns.append(os_column)
            else:
                raise ValueError(f"Unsupported column format: {type(col)}")
        
        return os_columns
    
    # ==================== 用户管理接口 ====================
    
    def get_current_user(self) -> Optional[str]:
        """
        获取当前用户信息
        
        Returns:
            Optional[str]: 当前用户名，格式为 username@host
        """
        if self.is_authenticated and self.current_username:
            return f"{self.current_username}@{self.current_user_host}"
        return None
    
    def is_user_authenticated(self) -> bool:
        """
        检查用户是否已认证
        
        Returns:
            bool: 是否已认证
        """
        return self.is_authenticated and self.session_id is not None
    
    def get_accessible_databases(self) -> List[str]:
        """
        获取当前用户可访问的数据库列表
        
        Returns:
            List[str]: 可访问的数据库列表
        """
        if not self.is_user_authenticated():
            return []
        
        try:
            all_databases = self.database_server.list_databases(self.session_id)
            # DatabaseServer的list_databases已经做了权限过滤
            return all_databases
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to get accessible databases: {e}")
            return []
    
    # ==================== 索引管理接口 ====================
    
    def create_index(self, table_name: str, column_name: str, index_name: str = None, 
                     is_primary: bool = False, key_type: str = 'int') -> bool:
        """
        创建索引
        
        Args:
            table_name: 表名
            column_name: 列名
            index_name: 索引名称（可选）
            is_primary: 是否为主键索引
            key_type: 键类型 ('int', 'string', 'float')
            
        Returns:
            bool: 创建成功返回True
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return False
        
        if not self.current_database:
            self.logger.error("ADAPTER", 0, "No database selected")
            return False
        
        try:
            if is_primary:
                result = self.database_server.execute_database_operation(
                    self.session_id, "create_primary_index", 
                    table_name=table_name, column_name=column_name, key_type=key_type
                )
            else:
                result = self.database_server.execute_database_operation(
                    self.session_id, "create_secondary_index",
                    table_name=table_name, column_name=column_name, 
                    index_name=index_name, key_type=key_type
                )
            return result
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to create index: {e}")
            return False
    
    def drop_index(self, index_name: str) -> bool:
        """
        删除索引
        
        Args:
            index_name: 索引名称
            
        Returns:
            bool: 删除成功返回True
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return False
        
        if not self.current_database:
            self.logger.error("ADAPTER", 0, "No database selected")
            return False
        
        try:
            engine = self.database_server.get_database_engine(self.session_id, self.current_database)
            if not engine:
                return False
            
            return engine.index_manager.drop_index(index_name)
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to drop index: {e}")
            return False
    
    def get_index_info(self, table_name: str = None) -> Dict[str, Any]:
        """
        获取索引信息
        
        Args:
            table_name: 表名（可选，如果不提供则返回所有索引信息）
            
        Returns:
            Dict[str, Any]: 索引信息
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return {}
        
        if not self.current_database:
            self.logger.error("ADAPTER", 0, "No database selected")
            return {}
        
        try:
            # 获取数据库实例
            db_instance = self.database_server.get_database_engine(self.session_id, self.current_database)
            if not db_instance:
                return {}
            
            # 检查是否有索引管理器
            if not hasattr(db_instance, 'index_manager'):
                self.logger.warn("ADAPTER", 0, "Database instance has no index manager")
                return {
                    'total_indexes': 0,
                    'table_name': table_name,
                    'indexes': {},
                    'message': 'Index manager not available'
                }
            
            try:
                index_stats = db_instance.index_manager.get_index_statistics()
                if not isinstance(index_stats, dict):
                    return {
                        'total_indexes': 0,
                        'table_name': table_name,
                        'indexes': {}
                    }
            except Exception as e:
                self.logger.warn("ADAPTER", 0, f"Failed to get index statistics: {e}")
                return {
                    'total_indexes': 0,
                    'table_name': table_name,
                    'indexes': {}
                }
            
            if table_name:
                # 过滤指定表的索引
                filtered_indexes = {}
                for index_name, stats in index_stats.get('indexes', {}).items():
                    if stats.get('table_name') == table_name:
                        filtered_indexes[index_name] = stats
                return {
                    'total_indexes': len(filtered_indexes),
                    'table_name': table_name,
                    'indexes': filtered_indexes
                }
            
            return index_stats
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to get index info: {e}")
            return {}
    
    # ==================== 系统监控接口 ====================
    
    def get_performance_stats(self) -> Dict[str, Any]:
        """
        获取性能统计信息
        
        Returns:
            Dict[str, Any]: 性能统计信息
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return {}
        
        if not self.current_database:
            self.logger.error("ADAPTER", 0, "No database selected")
            return {}
        
        try:
            # 获取数据库实例
            db_instance = self.database_server.get_database_engine(self.session_id, self.current_database)
            if not db_instance:
                return {}
            
            # 收集各种统计信息
            performance_stats = {
                'database': self.current_database,
                'session_id': self.session_id,
                'timestamp': __import__('time').time()
            }
            
            # 获取数据库统计信息
            try:
                db_stats = db_instance.get_database_stats()
                
                # 存储统计
                if 'storage_stats' in db_stats:
                    storage_stats = db_stats['storage_stats']
                    performance_stats['storage'] = {
                        'total_pages': storage_stats.get('total_pages', 0),
                        'pages_allocated': storage_stats.get('pages_allocated', 0),
                        'pages_read': storage_stats.get('pages_read', 0),
                        'pages_written': storage_stats.get('pages_written', 0)
                    }
                
                # 缓存统计  
                if 'cache_stats' in db_stats:
                    cache_stats = db_stats['cache_stats']
                    performance_stats['cache'] = {
                        'cache_size': cache_stats.get('cache_size', 0),
                        'cache_hits': cache_stats.get('cache_hits', 0),
                        'cache_misses': cache_stats.get('cache_misses', 0),
                        'hit_rate': cache_stats.get('hit_rate', 0.0)
                    }
            except Exception as e:
                self.logger.warn("ADAPTER", 0, f"Failed to get database stats: {e}")
            
            # 索引统计
            try:
                if hasattr(db_instance, 'index_manager'):
                    index_stats = db_instance.index_manager.get_index_statistics()
                    if isinstance(index_stats, dict):
                        performance_stats['indexes'] = {
                            'total_indexes': index_stats.get('total_indexes', 0),
                            'tables_with_indexes': index_stats.get('tables_with_indexes', 0)
                        }
            except Exception as e:
                self.logger.warn("ADAPTER", 0, f"Failed to get index stats: {e}")
            
            # 服务器级别统计
            try:
                server_stats = self.database_server.get_server_stats()
                if 'threads' in server_stats:
                    performance_stats['threads'] = server_stats['threads']
            except Exception as e:
                self.logger.warn("ADAPTER", 0, f"Failed to get server stats: {e}")
            
            return performance_stats
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to get performance stats: {e}")
            return {}
    
    def get_table_statistics(self, table_name: str) -> Dict[str, Any]:
        """
        获取表的详细统计信息
        
        Args:
            table_name: 表名
            
        Returns:
            Dict[str, Any]: 表统计信息
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return {}
        
        if not self.current_database:
            self.logger.error("ADAPTER", 0, "No database selected")
            return {}
        
        try:
            # 获取数据库引擎（实际上是数据库实例）
            db_instance = self.database_server.get_database_engine(self.session_id, self.current_database)
            if not db_instance:
                self.logger.error("ADAPTER", 0, f"Database instance not found: {self.current_database}")
                return {}
            
            # 基础表信息
            table_info = self.get_table_info(table_name)
            if not table_info:
                return {}
            
            # 记录数统计（通过查询获取）
            record_count = len(self.select_records(table_name))
            
            # 获取数据库统计信息
            try:
                db_stats = db_instance.get_database_stats()
            except Exception as e:
                self.logger.warn("ADAPTER", 0, f"Failed to get database stats: {e}")
                db_stats = {}
            
            # 页面使用统计（从表信息中获取）
            page_count = table_info.get('page_count', 0)
            
            # 索引统计（如果有索引管理器的话）
            index_count = 0
            indexes = {}
            try:
                if hasattr(db_instance, 'index_manager'):
                    index_stats = db_instance.index_manager.get_index_statistics()
                    if isinstance(index_stats, dict):
                        # 过滤该表的索引
                        table_indexes = {}
                        for idx_name, idx_info in index_stats.get('indexes', {}).items():
                            if idx_info.get('table_name') == table_name:
                                table_indexes[idx_name] = idx_info
                        indexes = table_indexes
                        index_count = len(table_indexes)
            except Exception as e:
                self.logger.warn("ADAPTER", 0, f"Failed to get index info: {e}")
            
            return {
                'table_name': table_name,
                'database': self.current_database,
                'record_count': record_count,
                'column_count': len(table_info.get('columns', [])),
                'page_count': page_count,
                'indexes': indexes,
                'index_count': index_count,
                'created_time': table_info.get('created_time'),
                'schema': table_info.get('columns', []),
                'database_stats': db_stats.get('storage_stats', {})
            }
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to get table statistics: {e}")
            return {}
    
    # ==================== 高级查询接口 ====================
    
    def execute_query_with_stats(self, query_func, *args, **kwargs) -> Dict[str, Any]:
        """
        执行查询并返回性能统计
        
        Args:
            query_func: 查询函数
            *args: 查询函数参数
            **kwargs: 查询函数关键字参数
            
        Returns:
            Dict[str, Any]: 包含结果和统计信息的字典
        """
        if not self.is_user_authenticated():
            return {'error': 'User not authenticated'}
        
        try:
            import time
            start_time = time.time()
            
            # 执行查询
            result = query_func(*args, **kwargs)
            
            end_time = time.time()
            execution_time = end_time - start_time
            
            return {
                'result': result,
                'execution_time': execution_time,
                'timestamp': start_time,
                'success': True
            }
        except Exception as e:
            return {
                'result': None,
                'error': str(e),
                'success': False
            }
    
    # ==================== 用户管理接口（仅限管理员） ====================
    
    def create_user(self, username: str, password: str, host: str = '%') -> bool:
        """
        创建新用户（需要管理员权限）
        
        Args:
            username: 用户名
            password: 密码
            host: 主机（默认为%表示任意主机）
            
        Returns:
            bool: 创建成功返回True
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return False
        
        try:
            return self.database_server.create_user(self.session_id, username, password, host)
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to create user: {e}")
            return False
    
    def drop_user(self, username: str, host: str = '%') -> bool:
        """
        删除用户（需要管理员权限）
        
        Args:
            username: 用户名
            host: 主机
            
        Returns:
            bool: 删除成功返回True
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return False
        
        try:
            return self.database_server.drop_user(self.session_id, username, host)
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to drop user: {e}")
            return False
    
    def grant_privilege(self, username: str, host: str, privilege: str, 
                       database: str = None, table: str = None) -> bool:
        """
        授予权限（需要管理员权限）
        
        Args:
            username: 用户名
            host: 主机
            privilege: 权限类型 (SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALL_PRIVILEGES等)
            database: 数据库名（可选）
            table: 表名（可选）
            
        Returns:
            bool: 授权成功返回True
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return False
        
        try:
            return self.database_server.grant_privilege(
                self.session_id, username, host, privilege, database, table
            )
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to grant privilege: {e}")
            return False
    
    def revoke_privilege(self, username: str, host: str, privilege: str,
                        database: str = None, table: str = None) -> bool:
        """
        撤销权限（需要管理员权限）
        
        Args:
            username: 用户名
            host: 主机
            privilege: 权限类型
            database: 数据库名（可选）
            table: 表名（可选）
            
        Returns:
            bool: 撤销成功返回True
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return False
        
        try:
            return self.database_server.revoke_privilege(
                self.session_id, username, host, privilege, database, table
            )
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to revoke privilege: {e}")
            return False
    
    def list_users(self) -> List[Dict[str, Any]]:
        """
        列出所有用户（需要管理员权限）
        
        Returns:
            List[Dict[str, Any]]: 用户列表
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return []
        
        try:
            return self.database_server.list_users(self.session_id)
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to list users: {e}")
            return []
    
    def get_user_privileges(self, username: str = None, host: str = None) -> List[Dict[str, Any]]:
        """
        获取用户权限信息
        
        Args:
            username: 用户名（可选，默认获取当前用户）
            host: 主机（可选）
            
        Returns:
            List[Dict[str, Any]]: 权限列表
        """
        if not self.is_user_authenticated():
            self.logger.error("ADAPTER", 0, "User not authenticated")
            return []
        
        # 如果没有指定用户，获取当前用户的权限
        if username is None:
            username = self.current_username
            host = self.current_user_host
        
        try:
            return self.database_server.get_user_privileges(self.session_id, username, host)
        except Exception as e:
            self.logger.error("ADAPTER", 0, f"Failed to get user privileges: {e}")
            return []
    
    # ==================== 批量操作接口 ====================
    
    def bulk_insert(self, table_name: str, records: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        批量插入记录
        
        Args:
            table_name: 表名
            records: 记录列表
            
        Returns:
            Dict[str, Any]: 批量操作结果
        """
        if not self.is_user_authenticated():
            return {'success': False, 'error': 'User not authenticated'}
        
        try:
            success_count = 0
            failed_count = 0
            errors = []
            
            for i, record in enumerate(records):
                try:
                    if self.insert_record(table_name, record):
                        success_count += 1
                    else:
                        failed_count += 1
                        errors.append(f"Record {i}: Insert failed")
                except Exception as e:
                    failed_count += 1
                    errors.append(f"Record {i}: {str(e)}")
            
            return {
                'success': True,
                'total_records': len(records),
                'success_count': success_count,
                'failed_count': failed_count,
                'errors': errors[:10]  # 只返回前10个错误
            }
        except Exception as e:
            return {'success': False, 'error': str(e)}
    
    def close(self):
        """关闭适配器"""
        self.disconnect()
        self.database_server.stop()
        self.logger.info("ADAPTER", 0, "DatabaseServerAdapter closed")
    
    def __enter__(self):
        """支持with语句"""
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """支持with语句"""
        self.close()
